package tests_dao;

import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.hibernate.Session;
import org.hibernate.cfg.Configuration;
import org.testng.Assert;
import org.testng.annotations.AfterClass;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;

import dao.CrudService;
import dao.CrudServiceImpl;
import entities.Currency;
import entities.ExchangeRate;

public class AddExchangeRateTest
{
	CrudService			crud_service	= new CrudServiceImpl();
	SimpleDateFormat	sdf				= new SimpleDateFormat("dd-MM-yyyy");

	@Test
	public void addExchangeRateTest () throws ParseException
	{
		// given
		final Long expectedRows = new Long("1");
		Currency abc = new Currency("abc", "abc currency");
		crud_service.addCurrency(abc);

		// when
		crud_service.addExchangeRate(new ExchangeRate(new Date(), abc, 1, new BigDecimal(6)));

		// when
		Session session = new Configuration().configure().buildSessionFactory().openSession();
		@SuppressWarnings("unchecked")
		Long result = (Long) session.createQuery("select count(*) from ExchangeRate").uniqueResult();
		session.close();

		Assert.assertEquals(result, expectedRows);

	}

	@Test
	public void addExchangeRateWithCascadeCurrencyTest () throws ParseException
	{
		Currency cascadeRelation = new Currency("TST", "test");
		crud_service.addExchangeRate(new ExchangeRate(new Date(), cascadeRelation, 1, new BigDecimal(6)));

		Session session = new Configuration().configure().buildSessionFactory().openSession();
		@SuppressWarnings("unchecked")
		Long result = (Long) session.createQuery("select count(*) from ExchangeRate").uniqueResult();
		session.close();

		Assert.assertEquals(result, new Long("1"));

	}

	@BeforeMethod
	public void beforeTest () throws ParseException
	{
		crud_service.clearDataBase();
	}

	@AfterClass
	public void afterClass ()
	{
		crud_service.clearDataBase();
	}
}
